// 成本同类对比
var numberFormate = iot.getNumberFormat("0.00");
var subLevelDevMap = {
    719 :{
        ele : 'E001',
        gas : 'G001'
    },
    720 :{
        ele : 'E009'
    },
    721 :{
        ele : 'E070'
    },
    722 :{
        ele : 'E276'
    },
    723 :{
        ele : 'E037',
        gas : 'G059'
    },
    724 :{
        ele : 'E401',
        gas : 'G002'
    }
}

/**
 * 通过空间id和时间获取用电对应的sql
 * @param workSpace
 * @param time
 * @returns {string}
 */
function getEleSql(workSpace, time) {
    return "select SUM(win.dvalue) totalSum " +
        " FROM iot_dev_data_win win " +
        " LEFT JOIN iot_dev dev on dev.id=win.dev_id " +
        " where 1=1 " +
        " and dev.sn='"+subLevelDevMap[workSpace].ele+"'" +
        " and win.data_type = '_用量'" +
        " and win.the_time like '"+ time +"%'";
}

/**
 * 通过空间id和时间获取燃气对应的sql
 * @param workSpace
 * @param time
 * @returns {string}
 */
function getGasSql(workSpace, time) {
    return "select SUM(win.dvalue) totalSum " +
        " FROM iot_dev_data_win win " +
        " LEFT JOIN iot_dev dev on dev.id=win.dev_id " +
        " where 1=1 " +
        " and dev.sn='"+ subLevelDevMap[workSpace].gas +"'" +
        " and win.data_type = '用量'" +
        " and win.the_time like '"+ time +"%'";
}

dev.action = function(resp,param){
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var preYearTime = getPreYearTime(theTime);
    var workSpace = param.workSpace;
    var db = iot.db();
    var timeSub = parseInt(theTime.substring(0, 4));

    var result1 = db.queryOne("select level, name, pid from energy_struc where id = " + workSpace);
    var strSql;
    if (result1.level == '1') {
        strSql = " and level = 1";
    } else {
        strSql = " and level = " + result1.level + " and name = '" + result1.name + "'";
    }

    //获取当前选择年份产量
    var yieldResult = db.queryOne("select SUM(dvalue) totalSum from iot_dev_data_win" +
        " where dev_id = 278 and the_time like '"+ theTime +"%'");
    var totalYield = yieldResult.totalSum;

    // 计算郑州工厂上一年产量
    var preYearSingleResult = db.queryOne("select SUM(dvalue) totalSum from iot_dev_data_win" +
        " where dev_id = 278 and the_time like '"+ preYearTime +"%'");
    var preYearYield = 0;
    if (preYearSingleResult.totalSum) {
        preYearYield = preYearSingleResult.totalSum;
    }

    var result = 0;
    if (timeSub >= 2019) {
        var factoryMap = db.getMapFrTable("factory", "name", "select factory, name from energy_struc where level = 1 and type = '成本'");
        // 当前年份的用量
        result = db.qry("select es.factory, res.es_id, res.totalSum from energy_struc es " +
            " INNER JOIN (select esp.energy_struc_id es_id, SUM(dev_win.dvalue) totalSum " +
            " from iot_dev_data_win dev_win," +
            " (select dev_id, name, energy_struc_id from energy_struc_prop where type = 2 and name = '成本'" +
            " and energy_struc_id in (select id from energy_struc where type = '成本'" + strSql + ")) esp " +
            " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
            " and dev_win.the_time like '"+ theTime +"%'" +
            " group by esp.energy_struc_id) res" +
            " on es.id = res.es_id order by totalSum desc");

        // 计算郑州工厂上一年总量的同比的数据
        var preYearResult = db.queryOne("select esp.name,SUM(dev_win.dvalue) totalSum from iot_dev_data_win dev_win," +
            " (select * from energy_struc_prop where type = 2 and name = '成本' and energy_struc_id = "+ workSpace +") esp" +
            " where dev_win.dev_id = esp.dev_id" +
            " and dev_win.data_type = esp.name" +
            " and dev_win.the_time like '"+ preYearTime +"%'");
        var preYearTotalSum = 0;
        if (preYearResult.totalSum) {
            preYearTotalSum = preYearResult.totalSum;
        }

        var factoryList = iot.list();
        var count = 0;
        var preValue = "";
        result.forAll(function (item) {
            // 如果数值一样，则排名不变化
            if (!item.totalSum.equals(preValue)) {
                preValue = item.totalSum;
                ++count;
            }
            //判断当前选择总数还是单车
            if (totalOrSingle.equals("total")) {
                var increase = "0%";
                if ("ZZ".equals(factoryMap[item.factory])) {
                    if (item.totalSum && preYearTotalSum != 0) {
                        var gain = (item.totalSum - preYearTotalSum) / preYearTotalSum; // 计算同比差值
                        increase = (gain * 100).toFixed(1) + "%";
                    }
                }
                factoryList.add({rank: count, name: item.factory, workshop: result1.name, useNum: numberFormate.format(item.totalSum), increase: increase});
            }else if (totalOrSingle.equals("single")) {
                var sum = 0; // 当前年份的单车用量
                if (item.totalSum && totalYield){
                    sum = item.totalSum / totalYield;
                }
                var increase = "0%";
                if ("ZZ".equals(factoryMap[item.factory])) { // 只有郑州工厂的有同比涨幅
                    var preYearSingle = 0;
                    if (preYearTotalSum != 0 && preYearYield != 0) {
                        preYearSingle = preYearTotalSum / preYearYield; // 上一年的单车用量
                        if (sum != 0 && preYearSingle != 0) {
                            var toFixedSum = numberFormate.format(sum);
                            var toFixedPreSingle = numberFormate.format(preYearSingle);
                            var gain = (toFixedSum - toFixedPreSingle) / toFixedPreSingle;
                            increase = (gain * 100).toFixed(1) + "%";
                        }
                    }
                }
                factoryList.add({rank: count, name: item.factory,workshop: result1.name, useNum: numberFormate.format(sum), increase: increase});
            }

        })

        // 如果工厂数据没有，则赋值为0
        for (var i in similarFactoryList) {
            var flag = false;
            for (var key in factoryList) {
                if (similarFactoryList[i].equals(factoryList[key].name)) {
                    flag = true;
                }
            }
            if (!flag) {
                factoryList.add({rank: count + 1, name: similarFactoryList[i],workshop: result1.name,  useNum: 0, increase: "0%"});
            }
        }
        var jsData = {
            content : factoryList
        };
        resp.setJsData(jsData);

    } else { // 计算2019年之前的数据

        // 今年的计算统计数据
        var totalCarbon = 0;
        var electricityResult = 0;
        var gasResult = 0;
        // 定义上一年数据的变量
        var preTotalCarbon = 0;
        var preYearElectricityResult = 0;
        var preYearGasResult = 0;
        //工厂  E001._用量*0.734 +  G001.用量*2.355
        if(subLevelDevMap[workSpace] && subLevelDevMap[workSpace].ele){
            electricityResult = db.queryOne(getEleSql(workSpace, theTime));
            preYearElectricityResult = db.queryOne(getEleSql(workSpace, preYearTime));
        }
        if(subLevelDevMap[workSpace] && subLevelDevMap[workSpace].gas){
            gasResult = db.queryOne(getGasSql(workSpace, theTime));
            preYearGasResult = db.queryOne(getGasSql(workSpace, preYearTime));
        }
        // 计算当前年的数据
        if(electricityResult && electricityResult.totalSum){
            totalCarbon = electricityResult.totalSum * 0.64;
        }
        if(gasResult && gasResult.totalSum){
            totalCarbon = totalCarbon + gasResult.totalSum * 3.6;
        }
        // 上一年的计算数据
        if (preYearElectricityResult.totalSum) {
            preTotalCarbon = preYearElectricityResult.totalSum * 0.64;
        }
        if (preYearGasResult.totalSum) {
            preTotalCarbon = preTotalCarbon + preYearGasResult.totalSum * 3.6;
        }
        var factoryList = iot.list();

        //判断当前选择总数还是单车
        if (totalOrSingle.equals("total")) {
            var increase = "0%";
            if (totalCarbon != 0 && preTotalCarbon != 0) {
                var gain = (totalCarbon - preTotalCarbon) / preTotalCarbon;
                increase = (gain * 100).toFixed(1) + "%";
            }
            factoryList.add({rank: 1, name: 'ZZ', useNum: numberFormate.format(totalCarbon),workshop: result1.name,  increase: increase});
        }else if (totalOrSingle.equals("single")) {
            // 当前年的单车成本
            if (totalCarbon != 0 && totalYield != 0){
                totalCarbon = totalCarbon / totalYield;
            }
            var preYearSingleCarbon = 0; // 上一年的单车成本
            // 计算上一年的单车成本
            if (preTotalCarbon != 0 && preYearYield != 0) {
                preYearSingleCarbon = preTotalCarbon / preYearYield;
            }
            var increase = "0%";
            // 计算同比涨幅
            if (totalCarbon != 0 && preYearSingleCarbon != 0) {
                var toFixedTotalCarbon = numberFormate.format(totalCarbon);
                var toFixedPreYearSingleCarbon = numberFormate.format(preYearSingleCarbon);
                var gain = (toFixedTotalCarbon - toFixedPreYearSingleCarbon) / toFixedPreYearSingleCarbon;
                increase = (gain * 100).toFixed(1) + "%";
            }
            factoryList.add({rank: 1, name: 'ZZ', useNum: numberFormate.format(totalCarbon),workshop: result1.name,  increase: increase});
        }

        for (var i in similarFactoryList) {
            if(!'ZZ'.equals(similarFactoryList[i])) {
                factoryList.add({rank:2, name: similarFactoryList[i],workshop: result1.name,  useNum: 0, increase: "0%"});
            }
        }
        var jsData = {
            content : factoryList
        };
        resp.setJsData(jsData);
    }

}
